package filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import pojo.User;
import service.ShiroService;

import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private ShiroService shiroService;

    //获取用户权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("------------------------------------");
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return null;
        }
        // List<String> menus = shiroService.getUserMenu(user.getUserName());
        SimpleAuthorizationInfo info = (SimpleAuthorizationInfo)session.getAttribute("info");
        if(info==null){
            info=new SimpleAuthorizationInfo();
            List<String> roles = shiroService.getRoleByUserName(user.getUserName());
            if (roles != null) {
                for (String role : roles) {
                    info.addRole(role);
                }
            }
            session.setAttribute("info", info);
        }
//        if (menus != null) {
//            for (String menu : menus) {
//                info.addStringPermission(menu);
//            }
//        }

        return info;
    }

    //执行登录的
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //从数据库读取用户名和密码
        User user = shiroService.getUserByUserName(token.getUsername());
        if (user != null) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(token.getUsername(), user.getPassword(), getName());
            if (info != null) {
                Subject subject = SecurityUtils.getSubject();
                Session session = subject.getSession();
                session.setAttribute("user", user);
            }
            return info;
        }
        return null;
    }
}
